﻿using QuickManager.Code.SiteMgr.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace QuickManager.Code.SiteMgr
{
    public class SiteGroupManager
    {
        static string DataDir = AppDomain.CurrentDomain.BaseDirectory + "/Data";
        static string DataXml = AppDomain.CurrentDomain.BaseDirectory + "Data/SiteGroup.xml";
        static XmlDocument document = new XmlDocument();

        static SiteGroupManager()
        {
            if (File.Exists(DataXml) == false)
            {
                Directory.CreateDirectory(DataDir);   //创建目录
                XmlElement root = document.CreateElement("SiteGroup");
                document.AppendChild(root);
                document.Save(DataXml); //保存XML内容
            }
        }

        public static List<GroupInfoModel> GetGroupList()
        {
            using (SQLiteDataContext context = DB.GetContext())
            {
                if (context.GetTable<GroupInfoModel>().ToList().Count == 0)
                {
                    //创建默认分组
                    context.GetTable<GroupInfoModel>().InsertOnSubmit(new GroupInfoModel()
                    {
                        GroupID = Guid.Empty.ToString(),
                        GroupName = "默认分组",
                        GroupType = "0"
                    });
                    context.SubmitChanges();
                }
                return context.GetTable<GroupInfoModel>().ToList()
                    .OrderBy(m => m.GroupType)
                    .OrderBy(m => m.GroupID)
                    .ToList();
            }
        }

        /// <summary>
        /// 创建分组
        /// </summary>
        /// <param name="group"></param>
        /// <returns></returns>
        public static void CreateGroup(GroupInfoModel group)
        {
            using (SQLiteDataContext context = DB.GetContext())
            {
                group.GroupID = Guid.NewGuid().ToString();
                context.GetTable<GroupInfoModel>().InsertOnSubmit(group);
                context.SubmitChanges();
            }
        }

        public static void DeleteGroup(string groupID) {

            using (SQLiteDataContext context = DB.GetContext())
            {
                GroupInfoModel groupInfo = context.GetTable<GroupInfoModel>()
                    .ToList()
                    .FirstOrDefault(m => m.GroupID == groupID);
                if (groupInfo.GroupID!=Guid.Empty.ToString())
                {
                    context.GetTable<GroupInfoModel>().DeleteOnSubmit(groupInfo);

                    context.SubmitChanges();
                }
            }
        }
    }
}
